import { defineStore } from 'pinia'
import request from '@/utils/request'

// 创建认证store
export const useAuthStore = defineStore('auth', {
  state: () => ({
    token: localStorage.getItem('token') || null,
    user: null,
    isAuthenticated: false
  }),
  
  actions: {
    // 设置token
    setToken(token) {
      this.token = token
      this.isAuthenticated = true
      // 保存到localStorage
      localStorage.setItem('token', token)
    },
    
    // 清除token
    clearToken() {
      this.token = null
      this.user = null
      this.isAuthenticated = false
      // 从localStorage移除
      localStorage.removeItem('token')
    },
    
    // 登录
    async login(credentials) {
      try {
        const response = await request.post('/user/login', credentials)
        
        console.log('Login response:', response.data); // 调试日志
        
        // 根据实际响应结构提取token和user
        // 尝试不同的可能路径
        let token, user;
        if (response.data.token && response.data.user) {
          // 直接在response.data中
          token = response.data.token;
          user = response.data.user;
        } else if (response.data.data && response.data.data.token && response.data.data.user) {
          // 在response.data.data中
          token = response.data.data.token;
          user = response.data.data.user;
        } else if (response.data.result) {
          // 可能在result字段中
          token = response.data.result.token;
          user = response.data.result.user;
        } else {
          throw new Error('Invalid login response structure');
        }
        
        // 设置token和用户信息
        this.setToken(token)
        this.user = user
        
        return { success: true, data: { token, user } }
      } catch (error) {
        // 清除可能存在的无效token
        this.clearToken()
        console.error('Login error:', error)
        return {
          success: false,
          error: error.response?.data?.message || error.message || '登录失败'
        }
      }
    },
    
    // 登出
    logout() {
      this.clearToken()
    },
    
    // 检查用户是否已认证
    checkAuth() {
      if (this.token) {
        this.isAuthenticated = true
      } else {
        this.isAuthenticated = false
      }
    }
  },
  
  getters: {
    // 获取当前用户
    currentUser: (state) => state.user,
    // 检查是否已认证
    isLoggedIn: (state) => state.isAuthenticated,
    // 检查是否是管理员
    isAdmin: (state) => state.user && state.user.role === 'admin'
  }
})